package com.shallowUniverse.process.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author Shuai Guo
 * @version 1.0
 * @description
 * @date 2021/7/26
 */
public class Builder<T> {

    private final Supplier<T> supplier;
    private final List<Consumer<T>> modifiers = new ArrayList<>();

    public Builder(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public static <T> Builder<T> of(Supplier<T> supplier) {
        return new Builder<T>(supplier);
    }

    public <P1> Builder<T> with(Consumer1<T, P1> consumer, P1 p1) {
        Consumer<T> c = instance -> consumer.accept(instance, p1);
        this.modifiers.add(c);
        return this;
    }

    public <P1, P2> Builder<T> with(Consumer2<T, P1, P2> comsumer, P1 p1, P2 p2) {
        Consumer<T> c = instance -> comsumer.accept(instance, p1, p2);
        this.modifiers.add(c);
        return this;
    }

    public T build() {
        T value = supplier.get();
        this.modifiers.forEach(consumer -> consumer.accept(value));
        this.modifiers.clear();
        return value;
    }

    @FunctionalInterface
    public interface Consumer1<T, P1> {
        void accept(T t1, P1 p1);
    }

    @FunctionalInterface
    public interface Consumer2<T, P1, P2> {
        void accept(T t1, P1 p1, P2 p2);
    }
}
